<template>
  <div>
    <div class="admin-class-new">
      <Tooltip
        :overlay-style="{ whiteSpace: 'normal', width: '375px' }"
        :get-popup-container="
          triggerNode => {
            return triggerNode.parentNode || document.body;
          }
        "
        :placement="'top'"
      >
        <QuestionCircleOutlined />
        <template #title>
          <!-- style="margin-bottom: 10px" -->
          <p>什么是管理人员？</p>
          <p>管理人员指：宿舍管理人员、学生年级主任、班主任。</p>
          <p
            >可进出范围：宿舍管理人员进出管理楼栋的房间，学生年级主任、班主任进出管理班级学生住宿房间</p
          >
        </template>
      </Tooltip>
      允许管理人员进出：
      <a-switch v-model:checked="adminChecked" checked-children="开" un-checked-children="关" />
    </div>
    <div class="main-list-box new-rulesd">
      <div v-for="(item, index) in ruleList" :key="index">
        <div class="main-item-box">
          <div class="flex items-center justify-between">
            <p class="list-title">时间组{{ index + 1 }}</p>
            <div
              v-if="ruleList.length > 1"
              class="flex items-center del-box"
              @click="delRule(item, index)"
            >
              <!-- eslint-disable -->
              <e v-html="delSvg('#999999')"></e>
              <e v-html="delSvg(setStyles.primaryColor)"></e>
              <!-- eslint-enable -->
              删除
            </div>
          </div>

          <Form ref="formRefs" name="dynamic_form_item" :model="item" :rules="formRules">
            <div class="h-58-new">
              <Form.Item label="规则名称" name="ruleName" class="z-m-b-18">
                <Input
                  :id="new Date().getTime()"
                  v-model:value.trim="item.ruleName"
                  class="name-input"
                  :show-count="true"
                  placeholder="请输入规则名称"
                  :maxlength="10"
                />
              </Form.Item>
              <Form.Item label="生效范围" name="area">
                <!-- <Select
                  ref="objectChangeRef"
                  v-model:value="item.area"
                  placeholder="请选择生效范围"
                  :options="areaTypeList"
                  :get-popup-container="triggerNode => triggerNode.parentNode"
                >
                </Select> -->
                <span v-if="!isDisabled" class="select-z">
                  <!-- :get-popup-container="triggerNode => props.accessControlRulesRef" -->
                  <!-- <Select
                    v-if="!isDisabled"
                    :id="`objectChangeRef${index}`"
                    v-model:value="item.area"
                    style="width: 100%"
                    :show-search="false"
                    :allow-clear="true"
                    :disabled="gradeIdListHis.length === 0"
                    name="area"
                    placeholder="请选择生效范围"
                    mode="multiple"
                    class="object-change"
                    :options="areaTypeList"
                    :get-popup-container="
                      triggerNode => {
                        return triggerNode.parentNode;
                      }
                    "
                    @deselect="delArea(index)"
                  >
                    <template #dropdownRender>
                      <div
                        v-if="item.gradeIdList && gradeIdListHis.length > 0"
                        class="object-change-down"
                        @mousedown="e => e.preventDefault()"
                      >
                        <a-checkbox
                          v-model:checked="item.isAreaAll"
                          :class="
                            item.gradeIdList.length > 0 &&
                            item.gradeIdList.length < areaTypeListCheck.length
                              ? 'checkbox-no-all'
                              : ''
                          "
                          @change="changeArea(`objectChangeRef${index}`, true, index)"
                          >全部</a-checkbox
                        >
                        <a-checkbox-group
                          v-model:value="item.gradeIdList"
                          :options="areaTypeListCheck"
                          @change="val => changeArea(`objectChangeRef${index}`, false, index)"
                        />
                      </div>
                    </template>
                  </Select> -->
                  <a-cascader
                    :id="`objectChangeRef${index}`"
                    v-model:value="item.area"
                    multiple
                    :options="sectionList"
                    placeholder="请选择"
                    allow-clear
                    :max-tag-count="3"
                    :disabled="gradeIdListHis.length === 0"
                    dropdown-class-name="micro-dormitory-grade-and-class"
                    :class="['my-grade-and-class', item.isAreaAll ? 'my-grade-and-none' : '']"
                    :get-popup-container="
                      triggerNode => {
                        return triggerNode.parentNode;
                      }
                    "
                    @change="value => onChangeGradeAndClass(value, index)"
                  >
                  </a-cascader>
                  <div class="select-icon">
                    <img src="@/assets/images/rule/icon_select_down.png" alt="" />
                    <!-- <down-outlined /> -->
                  </div>
                </span>

                <Select
                  v-else
                  v-model:value="item.area"
                  style="width: 100%"
                  :show-search="false"
                  name="area"
                  :options="areaTypeList"
                  disabled
                >
                </Select>
              </Form.Item>
            </div>
            <div class="time-change-box">
              <Form.Item label="时间规则" name="time">
                <span class="z-time-box-new">
                  <TimeRangePicker
                    v-model:value="item.time"
                    :get-popup-container="() => props.accessControlRulesRef"
                    :input-read-only="true"
                    format="HH:mm"
                    value-format="HH:mm"
                    @change="timeChange(index)"
                  >
                    <template #suffixIcon> </template>
                    <template #separator>
                      <span class="time-center">至</span>
                    </template>
                  </TimeRangePicker>
                  <div class="z-time-box-icon">
                    <img src="@/assets/images/rule/u_clock.png" alt="" />
                  </div>
                </span>
              </Form.Item>
              <Form.Item label="进出方向" name="accessDirection">
                <!-- :get-popup-container="() => props.accessControlRulesRef" -->
                <Select
                  ref="objectChangeRef"
                  v-model:value="item.accessDirection"
                  class="select-new"
                  placeholder="请选择进出方向"
                  :options="directionList"
                  :get-popup-container="
                    triggerNode => {
                      return triggerNode.parentNode;
                    }
                  "
                >
                </Select>
              </Form.Item>
            </div>
          </Form>
        </div>
        <span v-if="item.isErr" class="access-form-err">必填选项为空，请输入</span>
      </div>
    </div>
    <div
      :class="`flex items-center justify-center access-control-add-box ${
        ruleList.length >= 20 ? 'add-no-box' : ''
      }`"
      class="w-100"
      @click="addList"
      ><PlusOutlined class="mr-2" /> 单击此处添加
    </div>
  </div>
</template>

<script setup>
import { Form, Select, Input, TimePicker, message, Tooltip } from 'ant-design-vue';
import { ref, watch, computed, nextTick, defineProps, defineExpose, onMounted } from 'vue';
import { PlusOutlined, QuestionCircleOutlined } from '@ant-design/icons-vue';
import { useStore } from 'vuex';
import { getRgba } from '@/utils/validate.js';
import { delSvg } from '@/utils/svg.js';
import { gradeList, getSectionCodeList, gradeListNew } from '@/api/common';
import { getTimeGroupList, saveTimeGroup, getTimePermission } from '@/api/ruleSetting';
const { TimeRangePicker } = TimePicker;
const store = useStore();
const studentTimeList = ref([]);
const props = defineProps({
  accessControlRulesRef: null,
  isDisabled: {
    default: false,
    type: Boolean
  },
  list: {
    default: () => [{}],
    type: Array
  }
});
// 规则列表
let ruleList = ref([
  {
    id: '',
    ruleName: '', // 规则名称
    gradeIdList: [], // 年级id
    ruleType: 0, // 0学生 1教职工
    ruleStartTime: '', // 开始时间
    ruleStopTime: '', // 结束时间
    accessDirection: '1', // 进出方向 0进 1出    改后 1 进 2出
    area: ['0'],
    time: [],
    direction: '1',
    isAreaAll: true,
    isErr: false
  }
]);
const formRefs = ref(null);
let gradeIdList = ref([]);
let gradeIdListHis = ref([]);
// 表单检验规则
const formRules = ref({
  ruleName: [
    { required: true, message: '请输入规则名称', trigger: ['change', 'blur'] },
    { max: 10, message: '请输入正确的规则名称' }
  ],
  area: [{ required: true, message: '请选择生效范围', trigger: ['change', 'blur'], type: 'array' }],
  time: [{ required: true, message: '请选择时间规则', trigger: ['change', 'blur'], type: 'array' }],
  accessDirection: [{ required: true, message: '请选择进出方向', trigger: 'change' }]
});
const deleteArr = ref([]);
watch(
  () => ruleList.value,
  val => {
    val.forEach(item => {
      // console.log(item, '22');
      // if (item.ruleName.length && item.time.length && item.area.length) {
      //   item.isErr = false;
      // }
    });
  },
  { deep: true }
);
onMounted(() => {
  getSection();
  // GetTimePermission();
  console.log('传过来的数组是什么', props.list);
  // studentTimeList.value.forEach((item, index) => {
  //       item.time = []
  //       item.time[0] = item.ruleStartTime;
  //       item.time[1] = item.ruleStopTime;
  //     });
});
function cancelRed() {
  ruleList.value.forEach((item, index) => {
    item.isErr = false;
  });
}
function validateFields() {
  console.log('走进来咯热门');
  formRefs.value.validateFields();
}
function GetTimeGroupList(type) {
  let data = {
    ruleType: type
  };
  getTimeGroupList(data).then(res => {
    console.log('查询宿舍时间组-里层', res, gradeIdList.value.length);
    if (res.data.code === 200 && res.data.data.length > 0) {
      // studentTimeList.value = res.data.data;
      ruleList.value = res.data.data;
      ruleList.value.forEach((item, index) => {
        item.time = [];
        item.time[0] = item.ruleStartTime;
        item.time[1] = item.ruleStopTime;
        item.accessDirection = item.accessDirection + '';
        // item.gradeIdList = ['342331051920285719', '342331051920285717', '342331051920285715'];
        if (item.gradeIdList) {
          if (
            item.gradeIdList.length === gradeIdList.value.length ||
            gradeIdList.value.length === 0
          ) {
            item.area = defaultAreaData.value;
            item.isAreaAll = true;
          } else {
            item.isAreaAll = false;
            item.area = disposeData(item.gradeIdList);
            console.log(item.area, 'item.area');
          }
        }
      });
    }
  });
}
// 生效范围下拉菜单
const areaTypeList = ref([
  {
    label: '全部',
    value: '0'
  }
]);
const areaTypeListCheck = ref([]);
// 进出方向下拉菜单
const directionList = ref([
  {
    label: '进',
    value: '1'
  },
  {
    label: '出',
    value: '2'
  }
]);
// 获取年级列表
function getGradeList(code, index) {
  gradeListNew(code).then(res => {
    console.log('获取年级列表888', res);
    if (res.data.code === 200) {
      // gradeIdList.value = [];
      // gradeIdListHis.value = [];
      let data = res.data.data;
      // let data = [];
      let gradeIds = [];

      if (data.length > 0) {
        data.forEach((item, index) => {
          item.label = item.gradeName + '住宿';
          item.value = item.gradeId;
          item.isLeaf = true;
          areaTypeList.value.push(item);
          areaTypeListCheck.value.push(item);
          gradeIds.push(item.gradeId);
          ruleList.value.forEach(item1 => {
            item1.gradeIdList.push(item.value);
          });
          gradeIdList.value.push(item.value);
        });
      }
      console.log(gradeIds, 'gradeIds');
      sectionList.value[index].gradeIds = gradeIds;
      sectionList.value[index].children = data;
      gradeIdListHis.value.push(...data);
      // 查询宿舍时间组 0 是学生 1是教职工
    }
  });
}
const sectionList = ref([]);
// 获取学段
const defaultAreaData = ref([['0']]);
const getSection = () => {
  getSectionCodeList().then(async res => {
    // console.log('获取学段的res', res);
    if (res.data.code === 200) {
      let list = res.data.data;
      sectionList.value = list;
      sectionList.value.forEach((item, index) => {
        item.label = item.sectionName;
        item.value = item.sectionCode;
        item.isLeaf = false;
        defaultAreaData.value.push([item.sectionCode]);
        getGradeList(item.sectionCode, index);
      });
      if (sectionList.value === 1) {
        await getGradeList(sectionList.value[0].sectionCode, 0);
      } else if (sectionList.value === 2) {
        await getGradeList(sectionList.value[0].sectionCode, 0);
        await getGradeList(sectionList.value[1].sectionCode, 1);
      } else if (sectionList.value === 3) {
        await getGradeList(sectionList.value[0].sectionCode, 0);
        await getGradeList(sectionList.value[1].sectionCode, 1);
        await getGradeList(sectionList.value[2].sectionCode, 2);
      }
      sectionList.value.push({
        label: '全部',
        value: '0'
      });
      if (sectionList.value.length === 1 || gradeIdList.value.length === 0) {
        console.log('ppp');
        ruleList.value.forEach((item, index) => {
          item.gradeIdList = [];
          item.area = [];
        });
      }
      // console.log(store.state.user.STATE_USER.userInfo.id, 'store.state.user.STATE_USER');
      // 查询宿舍时间组 0 是学生 1是教职工
      // GetTimeGroupList(0);
    }
  });
};
// 定义颜色变量
const setStyles = computed(() => {
  return {
    '--primaryColor': store.state.user.primaryColor,
    primaryColor: store.state.user.primaryColor,
    backgroundColor: getRgba(store.state.user.primaryColor, 0.1)
  };
});
// 新增规则列表
const addList = () => {
  if (ruleList.value.length >= 20) return;
  ruleList.value.push({
    // id: '',
    ruleName: '', // 规则名称
    gradeIdList: gradeIdList.value, // 年级id
    ruleType: 0, // 0学生 1教职工
    ruleStartTime: '', // 开始时间
    ruleStopTime: '', // 结束时间
    accessDirection: '1', // 进出方向 0进 1出  1 2
    area: gradeIdListHis.value.length > 0 ? defaultAreaData.value : [],
    time: [],
    direction: '1',
    isAreaAll: true,
    isErr: false
  });
  nextTick(() => {
    console.log(document.getElementsByClassName('main-list-box')[0]);
    document.getElementsByClassName('main-list-box')[0].scrollTop = 999999;
  });
};
// 删除规则
const delRule = (item, index) => {
  // ruleList.value.splice(index, 1);
  if (item.id && item.id !== null) {
    deleteArr.value.push(item.id);
  }

  ruleList.value.splice(index, 1);
};
const objectChangeRef = ref('');

// 选择生效返回
const changeArea = (vhtml, isAll, index) => {
  vhtml ? document.getElementById(vhtml).focus() : '';
  console.log(isAll, 'val');
  // let all = val.filter(item => item.length === 0);
  if (isAll) {
    if (ruleList.value[index].isAreaAll) {
      ruleList.value[index].area = ['0'];
      ruleList.value[index].gradeIdList = gradeIdList.value;
    } else {
      ruleList.value[index].area = [];
      ruleList.value[index].gradeIdList = [];
    }
  } else {
    // ruleList.value[index].areaCheck = [...ruleList.value[index].area];
    ruleList.value[index].area = [...ruleList.value[index].gradeIdList];
    if (ruleList.value[index].gradeIdList.length === gradeIdList.value.length) {
      ruleList.value[index].area = ['0'];
      ruleList.value[index].gradeIdList = gradeIdList.value;
      ruleList.value[index].isAreaAll = true;
    } else {
      ruleList.value[index].area = [...ruleList.value[index].gradeIdList];
      ruleList.value[index].isAreaAll = false;
    }
  }
};
// 删除生效范围回调
const delArea = index => {
  // ruleList.value[index].area = [];
  ruleList.value[index].gradeIdList = [...ruleList.value[index].area];
  ruleList.value[index].isAreaAll = false;
};
function timeChange(index) {
  console.log('选择的时间是什么', index);
  ruleList.value[index].ruleStartTime = ruleList.value[index].time[0];
  ruleList.value[index].ruleStopTime = ruleList.value[index].time[1];

  if (
    time_to_sec(ruleList.value[index].ruleStartTime) -
      time_to_sec(ruleList.value[index].ruleStopTime) ===
    0
  ) {
    message.error('结束时间不能等于开始时间');
    ruleList.value[index].ruleStartTime = '';
    ruleList.value[index].ruleStopTime = '';
    ruleList.value[index].time = [];
  }
}
function time_to_sec(time) {
  if (time !== null) {
    let s = '';
    let hour = time.split(':')[0];
    let min = time.split(':')[1];
    let sec = time.split(':')[2];
    s = Number(hour * 3600) + Number(min * 60);
    return s;
  }
}
function emptyDel() {
  deleteArr.value = [];
}

// 生效范围选择回调
const onChangeGradeAndClass = (value, index) => {
  console.log(value, 'value');

  let area = [...value];
  let isAreaAll = ruleList.value[index].isAreaAll;
  if (area.length > 1 && area[0][0] === '0') {
    area.shift();
  }
  let data = area.filter(item => item.length === 1);
  let length = sectionList.value.length - 1;
  let a = area.length === length;
  let b = data.length === length;
  if (a && b && isAreaAll) {
    area = [];
  }
  if (a && b && !isAreaAll) {
    isAreaAll = true;
  } else {
    isAreaAll = false;
  }
  if (isAreaAll) {
    area.unshift(['0']);
  }
  ruleList.value[index].area = area;
  ruleList.value[index].isAreaAll = isAreaAll;
};
// 处理已选择的数据
const disposeData = val => {
  let arr = [];
  let defaultData = [['0']];
  sectionList.value.forEach(item => {
    defaultData.push([item.value]);
    if (item.children) {
      item.children.forEach(itemChild => {
        if (val.includes(itemChild.value)) {
          arr.push([item.value, itemChild.value]);
        }
      });
    }
  });
  console.log(arr, 'arr');
  return arr.length ? arr : defaultData;
};
const permissionData = ref({ id: '' });
function GetTimePermission(type) {
  getTimePermission().then(res => {
    console.log('查询权限', res);
    if (res.data.code === 200) {
      permissionData.value = res.data.data;
      // console.log(permissionData.value, ' permissionData.value');
      // if (res.data.data.allowAdmin) {
      adminChecked.value = res.data.data.allowAdmin === 1;
      // }
      // console.log(adminChecked.value, ' adminChecked.value');
    }
  });
}
const adminChecked = ref(false);
const setPrimaryColor = computed(() => store.state.user.primaryColor);
const backgroundColorValue = computed(() => getRgba(store.state.user.primaryColor, 0.1));
defineExpose({
  ruleList,
  deleteArr,
  validateFields,
  cancelRed,
  gradeIdListHis,
  getGradeList,
  GetTimeGroupList,
  getSection,
  sectionList,
  gradeIdList,
  emptyDel,
  adminChecked,
  GetTimePermission,
  permissionData
});
</script>

<style lang="less" scoped>
@import url('./accessControlRules.less');
.access-control-main-box {
  padding: 15px 20px 0 40px;
}
.access-control-add-box:hover {
  cursor: pointer;
  border-color: v-bind('setStyles.primaryColor');
  color: v-bind('setStyles.primaryColor');
}
// .w-100 {
//   width: 100%;
// }
.z-m-b-18 {
  // margin-bottom: 18px !important;
}
.h-58-new {
  height: 58px;
}
::v-deep(.micro-dormitory-grade-and-class) {
  height: 150px;
  max-width: 300px;
  .micro-dormitory-cascader-menu:first-child {
    .micro-dormitory-cascader-menu-item:last-child {
      display: none;
    }
  }
  .micro-dormitory-cascader-menu {
    overflow-y: auto;
    overflow-x: hidden;
    height: 150px;
  }
  .micro-dormitory-cascader-menu-item {
    width: 150px;
  }
  .micro-dormitory-cascader-menu-item-content {
    width: 100px;
    white-space: nowrap !important;
    overflow: hidden !important;
    text-overflow: ellipsis !important;
  }
  .micro-dormitory-cascader-checkbox-inner {
    border-radius: 2px;
  }
  .micro-dormitory-cascader-menu-item {
    padding: 5px 8px;
  }
  .micro-dormitory-cascader-menu-item:hover {
    background-color: transparent;
    color: v-bind(setPrimaryColor);
  }
  .micro-dormitory-cascader-menu-item-active {
    color: v-bind(setPrimaryColor);
    background-color: v-bind(backgroundColorValue) !important;
  }
  .micro-dormitory-cascader-checkbox-indeterminate {
    .micro-dormitory-cascader-checkbox-inner {
      border-color: v-bind(setPrimaryColor);
    }
  }
}
::v-deep(.my-grade-and-none) {
  .micro-dormitory-select-selection-overflow-item {
    display: none;
  }
  .micro-dormitory-select-selection-overflow-item:first-child {
    display: block;
  }
}
.admin-class-new {
  font-size: 16px;
  color: #222222;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  width: 375px;
  span {
    font-size: 14px;
    color: #999999;
    cursor: pointer;
    margin-right: 4px;
  }
  ::v-deep(.anticon-question-circle:hover) {
    color: v-bind(setPrimaryColor);
  }
}
::v-deep(.micro-dormitory-tooltip-content) {
  width: 375px;
  font-size: 14px;
  line-height: 22px;
  .micro-dormitory-tooltip-inner {
    box-sizing: border-box;
    padding-left: 14px;
  }
}
</style>
